package com.eastedu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eastedu.common.util.SchoolGroupMappingUtil;
import com.eastedu.repository.question.mapper.QuestionBasicInfoMapper;
import com.eastedu.repository.question.mapper.QuestionSourceMapper;
import com.eastedu.repository.question.po.QuestionBasicInfoPO;
import com.eastedu.repository.question.po.QuestionSourcePO;
import com.eastedu.service.AbstractDataSyncService;
import com.eastedu.service.DataSourceService;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 〈〉
 *
 * @author ZHISHUAI.ZHANG
 * @since 2021 /7/28
 */
@Service("question-source")
@DS("question")
public class QuestionDataSourceServiceImpl extends AbstractDataSyncService<QuestionBasicInfoPO> implements DataSourceService {

    private final QuestionSourceMapper questionSourceMapper;

    /**
     * Instantiates a new Question data source service.
     *
     * @param questionBasicInfoMapper the question basic info mapper
     * @param questionSourceMapper    the question source mapper
     */
    public QuestionDataSourceServiceImpl(QuestionBasicInfoMapper questionBasicInfoMapper, QuestionSourceMapper questionSourceMapper) {
        super(questionBasicInfoMapper);
        this.questionSourceMapper = questionSourceMapper;
        /// super.addScriptByTableName("t_question_basic_info");
        super.addScript("UPDATE t_question_basic_info t1 INNER JOIN t_question_source t2 ON t1.id = t2.question_id\n" +
                                "SET t1.sync_state = 0 \n" +
                                "WHERE school_group_id IS NULL OR school_group_id = 0");
    }

    @Override
    protected void updateContent(QuestionBasicInfoPO questionBasicInfoPo) {
        final List<QuestionSourcePO> questionSourcePoList = getQuestionSourceList(questionBasicInfoPo);
        questionSourcePoList.forEach(o -> {
            o.setSchoolGroupId(SchoolGroupMappingUtil.mappingId(o.getOrganization()));
            this.questionSourceMapper.updateById(o);
        });
        questionBasicInfoPo.setSources(JSONObject.toJSONString(questionSourcePoList));
    }

    private List<QuestionSourcePO> getQuestionSourceList(QuestionBasicInfoPO questionBasicInfoPo) {
        return this.questionSourceMapper.selectList(Wrappers.<QuestionSourcePO>lambdaQuery()
                                                            .eq(QuestionSourcePO::getQuestionId, questionBasicInfoPo.getId()))
                ;
    }
}